import axios from './base'
import CryptoJS from 'crypto-js';
import qs from 'qs';

// 获取logo信息
export const getLogoInfo = (data) => {
  return axios.post('/openapi-uc/app-setting/logoinfo', data).then(res => {
    return res
  })
}
// 获取logo信息
export const captchaView = (data) => {
  return axios.get('/openapi-uc/captcha/view', data).then(res => {
    return res
  })
}

// 获取第三方登录配置信息
export const getAllowWay = () => {
  return axios.get('/openapi-uc/sys/getAllowWay').then(res => {
    return res
  })
}

// 获取token
export const getToken = (data) => {
  // 每次请求前删除双因子认证
  localStorage.removeItem('doubleAuthentic')
  let params = {
    ...data
  }
  let S2FACKey = params.username + '_S2FAC'

  params.C2FAC = localStorage.getItem(S2FACKey)
    ? localStorage.getItem(S2FACKey)
    : new Date().getTime()

  if (params.grant_type === 'password') {
    let key = CryptoJS.enc.Utf8.parse(window.$app.appKey)

    params.password = CryptoJS.AES.encrypt(params.password, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
  }

  if (
    window.$ui.urlQuery.parent_accredit_code &&
    !window.$ui.isEmptyValue(window.$ui.urlQuery.parent_accredit_code)
  ) {
    params.accredit_code = window.$ui.urlQuery.parent_accredit_code
  }

  if (window.$app.appType === 'mobile') {
    params.client_type = window.$ui.client.os.name === 'iOS' ? '3' : '2'
  } else if (window.$app.appType === 'pc' || window.CefSharp) {
    params.client_type = '1'
  }

  Object.keys(params).forEach((key) => {
    if (params[key] === '') {
      delete params[key]
    }
  })

  return axios({
    method: 'post',
    url: '/openapi-uc/oauth/token',
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    data: qs.stringify({}),
    params: {
      client_id: window.$app.appId,
      client_secret: window.$app.appKey,
      grant_type: 'password',
      version: '01',
      ...params
    }
  }).then(res => {
    return res
  }).catch(err => {
    console.log(err)
    return Promise.reject(err)
  })
}

// 获取token
export const getStudentTokenByParent = (data) => {
  let params = {
    ...data
  }
  if (window.$ui.urlQuery.clientType && !window.$ui.isEmptyValue(window.$ui.urlQuery.clientType)) {
    params.clientType = window.$ui.urlQuery.clientType
  } else if (window.$app.appType === 'pad') {
    params.clientType = params.clientType ? params.clientType : window.$ui.client.os.name === 'iOS' ? '3' : '2'
  } else {
    params.clientType = '4'
  }

  params.deviceType = window.$ui.urlQuery.deviceType || '0'

  Object.keys(params).forEach((key) => {
    if (params[key] === '') {
      delete params[key]
    }
  })

  return axios({
    method: 'post',
    url: '/openapi-uc/oauth2.0/getStudentTokenByParent',
    params: {
      appId: window.$app.appId,
      deviceType: '0',
      clientType: '1',
      ...params
    }
  }).then(res => {
    return res
  }).catch(err => {
    console.log(err)
    return Promise.reject(err)
  })
}

// 获取用户信息
export const getUser = (data) => {
  return axios.get('/openapi-uc/uc/getUserByToken/' + data.accessToken).then(res => {
    return res
  }).catch(err => {
    console.log(err)
    return Promise.reject(err)
  })
}

export const getUserRightList = (data) => {
  return axios.post('/openapi-uc/uc/getUserRightList', {
    appId: window.$app.appId,
    addrType: '2',
    ...data
  }).then(res => {
    return res
  })
}

// 获取班级信息
export const joinSearchClasses = (data) => {
  return axios.post('/openapi-uc/base/joinSearchClasses', {
    "name":"",
    "grade":"",
    "orgId":"TWPAAS1200000000002",
    "status":[1],
    "pageNo":1,
    "numPerPage":9999,
    "orderMethods":[{"field":"gradeName","method":"ASC"}],
    ...data
  }).then(res => {
    return res
  })
}

// 获取任教信息
export const queryTeachs = (data) => {
  let params = {
    ...data
  }
  if (window.$ui.urlQuery.clientType && !window.$ui.isEmptyValue(window.$ui.urlQuery.clientType)) {
    params.clientType = window.$ui.urlQuery.clientType
  } else if (window.$app.appType === 'pad') {
    params.clientType = params.clientType ? params.clientType : window.$ui.client.os.name === 'iOS' ? '3' : '2'
  } else {
    params.clientType = '4'
  }

  params.deviceType = window.$ui.urlQuery.deviceType || '0'

  Object.keys(params).forEach((key) => {
    if (params[key] === '') {
      delete params[key]
    }
  })
  return axios.post('/openapi-base/base/queryTeachs', {
    classStatus: '1',
    classType: '2',
    numPerPage: 100,
    pageNo: 1,
    forceOrderBySubjectId: true,
    ...params
  }).then(res => {
    return res
  })
}

// 获取学生班级信息
export const getClass = (data) => {
  return axios.post('/openapi-base/base/getClass', {
    classType: '2',
    ...data
  }).then(res => {
    return res
  })
}

// 获取学生信息
export const getStudentInfo = (data) => {
  return axios.post('/openapi-base/base/getStudentInfo', {
    classType: '2',
    ...data
  }).then(res => {
    return res
  })
}

// 获取配置信息
export const getSystemConfigsByKeys = (data) => {
  return axios.post('/openapi-base/base/getSystemConfigsByKeys', {
    classType: '2',
    ...data
  }).then(res => {
    return res
  })
}

// 获取二维码
export const getTeachQRCode = (data) => {
  return axios({
    method: 'post',
    url: `${window.$app.apiBaseUrl.prepareapi}/common/getTeachQRCode`,
    data: {
      ...data
    }
  }).then(res => {
    return res
  })
}

// 获取扫码成功
export const screenSuccess = (data) => {
  return axios({
    method: 'post',
    url: `${window.$app.apiBaseUrl.prepareapi}/common/screenSuccess`,
    data: {
      ...data
    }
  }).then(res => {
    return res
  })
}

// 查询用户
export const searchUserByName = (data) => {
  return axios.post('/openapi-uc/uc/search', {
    "province":"",
    "departmentId":"",
    "islocked":false,
    "city":"",
    "parentOrgId":"",
    "fuzzyMatch":true,
    "userId":"",
    "roleId":"",
    "loginName":"",
    "realName":"",
    "orgId":"",
    "orgName":"",
    "areaId":"",
    "loginEmail":"",
    "loginMobile":"",
    "idCardNo":"",
    "status":"1",
    "numPerPage":10,
    "pageNo":1,
    "createTime":null,
    "lastModifyTime":null,
    "queryTree":{
      "orderMethods":[{
        "field":"lastModifyTime",
        "method":"DESC"
      }],
      "pagination":{
        "numPerPage":10,
        "pageNo":1
      }
    },
    ...data
  }).then(res => {
    return res
  })
}

// 查询顶级机构
export const getTopOrg = (data) => {
  return axios.post('/openapi-uc/org/getTopOrg', {
    "singleTable": false,
    "conditions":[{"fieldName":"incloudParent","fieldValues":["1"],"operator":"EQUAL","prepender":"AND"}],"pagination":{"calTotal":false,"numPerPage":3000,"pageNo":1,"startNum":0}
  }).then(res => {
    return res
  })
}
// 查询子机构
export const getOrgsChildOrg = (data) => {
  return axios.post('/openapi-uc/org/getOrgsChildOrg', {
    "singleTable":false,"conditions":[{"fieldName":"incloudParent","fieldValues":["1"],"operator":"EQUAL","prepender":"AND"},{"fieldName":"curOrgId","fieldValues":[data.orgId||"TWPAAS1200000000393"],"operator":"IN","prepender":"AND"},{"fieldName":"orgTypeList","fieldValues":["0","1","2","3","4"],"operator":"IN","prepender":"AND"}],"pagination":{"calTotal":false,"numPerPage":3000,"pageNo":1,"startNum":0}
  }).then(res => {
    return res
  })
}

// 按班级查询学生
export const queryStudents = (data) => {
  return axios.post('/openapi-base/base/queryStudents', {
    "province":"",
    "departmentId":"",
    "islocked":false,
    "city":"",
    "parentOrgId":"",
    "fuzzyMatch":true,
    "userId":"",
    "roleId":"",
    "loginName":"",
    "realName":"",
    "orgId":"",
    "orgName":"",
    "areaId":"",
    "loginEmail":"",
    "loginMobile":"",
    "idCardNo":"",
    "status":"1",
    "numPerPage":10,
    "pageNo":1,
    "createTime":null,
    "lastModifyTime":null,
    "queryTree":{
      "orderMethods":[{
        "field":"lastModifyTime",
        "method":"DESC"
      }],
      "pagination":{
        "numPerPage":10,
        "pageNo":1
      }
    },
    ...data
  }).then(res => {
    return res
  })
}

// 按机构查老师
export const searchTeachers = (data) => {
  return axios.post('/openapi-uc/uc/search', {
    "province":"","departmentId":"","islocked":false,"city":"","parentOrgId":"","fuzzyMatch":true,"userId":"","roleId":"1000000002","loginName":"","realName":"","orgName":"","areaId":"","loginEmail":"","loginMobile":"","idCardNo":"","status":"1","numPerPage":9999,"pageNo":1,"createTime":null,"lastModifyTime":null,"queryTree":{"orderMethods":[{"field":"lastModifyTime","method":"DESC"}],"pagination":{"numPerPage":9999,"pageNo":1}},
    "orgId":"TWPAAS1200000000002",
    ...data
  }).then(res => {
    return res
  })
}

// 获取信任码
export const getAccreditCode = (path, params, target) => {
  var token = window.$app.user.token

  if (typeof params === 'string') {
    target = params
    params = null
  }

  if (path && target !== '_self') {
    target = '_blank'
  }

  let requestParams = {
    accessToken: token,
    userId: window.$app.user.userId
  }

  if (params && params.authAppId) {
    // 添加域控参数
    requestParams.authAppId = params.authAppId
    delete params.authAppId
  }

  return axios.post('/openapi-uc/accreditcode/getAccreditCode', requestParams).then(data => {
    var serverResult = data.serverResult
    var responseEntity = data.responseEntity

    if (serverResult.resultCode === '200' && responseEntity.accreditCode) {
      window.$ui.setAuth({
        'accreditCode': responseEntity.accreditCode,
        'accreditUrl': 'accredit_code=' + responseEntity.accreditCode + '&access_token=' + token + '&token=' + token
      })
      // window.Vue.set(window.$app.user, 'accreditCode', responseEntity.accreditCode)
      // window.Vue.set(window.$app.user, 'accreditUrl', 'accredit_code=' + responseEntity.accreditCode + '&access_token=' + token + '&token=' + token)

      // if (window.$lib.vm) {
      //   window.$lib.vm.$forceUpdate()
      // }

      if (path) {
        path = path + (path.indexOf('?') === -1 ? '?' : '&') + 'accredit_code=' + responseEntity.accreditCode + '&access_token=' + token + '&token=' + token + (params ? '&' + window.$ui.qs.stringify(params) : '')

        if (target === '_self') {
          window.location.href = path
        } else {
          window.$ui.openWin(path, '_blank')
        }
      } else {
        return responseEntity.accreditCode
      }
    } else if (serverResult.resultCode === '10000') {
      window.$ui.msgBox({
        title: '请登录',
        type: 'warning',
        message: '登录状态已过期，或在其他设备上登录！',
        confirmButtonText: '确定',
        showCancelButton: false,
        showClose: false
      }).then(() => {
        window.$ui.delAuth()
      })
    } else if (serverResult.resultCode === '8028') {
      window.$ui.msg(serverResult.resultMessage)
      return new Error('failed to get the acredit code.')
    } else {
      return new Error('failed to get the acredit code.')
    }
  }).catch(e => {
    console.error(e)
  })
}

export const openApp = (path, params, target) => {
  if (params && params.userToken) {
    axios.get(window.$app.ecoGateway + '/openapi-uc/oauth/checkToken?access_token=' + params.userToke).then(() => {
      gotoUrl(path, target)
    }).catch( (err) => {
      console.log(err)
      getAccreditCode(path, params, target)
    })
  } else {
    getAccreditCode(path, params, target)
  }
}

export const gotoUrl = (url, target) => {
  if (/{accreditCode}$/.test(url)) {
    openApp(url.replace(/{accreditCode}$/, ''), null, target || '_self')
  } else {
    const toUrl = new URL(url, window.location.href)
    const toPath = toUrl.origin + toUrl.pathname
    const currentPath = window.location.origin + window.location.pathname

    if (toPath !== currentPath) {
      if (target === '_blank') {
        window.$ui.openWin(url)
      } else {
        window.location.href = url
      }
    }
  }
}